/* eslint-disable no-unused-vars */
import React, { useState, useEffect } from "react";

import {
  ProForm,
  ProFormDependency,
  ProFormList,
  ProFormText,
  ProFormSelect,
  ProFormSwitch,
  ProFormGroup,
  ProFormDigitRange,
  ProFormDigit,
} from "@ant-design/pro-components";

import {
  DndContext,
  closestCenter,
  TouchSensor,
  MouseSensor,
  useSensor,
  useSensors,
  DragOverlay,
} from "@dnd-kit/core";

import {
  arrayMove,
  SortableContext,
  sortableKeyboardCoordinates,
  rectSortingStrategy,
} from "@dnd-kit/sortable";
import SortableItem from "./sortableitem";
import Item from "./item";
import { v4 as uuidv4 } from "uuid";
import { Button, Divider, Form } from "antd";
import { CopyFilled, DeleteFilled } from "@ant-design/icons";
const inputTypes = [
  { label: "密码输入框", value: "password" },
  { label: "金额输入框", value: "money" },
  { label: "文本域", value: "textarea" },
  { label: "日期", value: "date" },
  { label: "日期时间", value: "dateTime" },
  { label: "周", value: "dateWeek" },
  { label: "月", value: "dateMonth" },
  { label: "季度输入", value: "dateQuarter" },
  { label: "年份输入", value: "dateYear" },
  { label: "日期区间", value: "dateRange" },
  { label: "日期时间区间", value: "dateTimeRange" },
  { label: "时间", value: "time" },
  { label: "时间区间", value: "timeRange" },
  { label: "文本框", value: "text" },
  { label: "下拉框", value: "select" },
  { label: "树形下拉框", value: "treeSelect" },
  { label: "多选框", value: "checkbox" },
  { label: "星级组件", value: "rate" },
  { label: "单选框", value: "radio" },
  { label: "按钮单选框", value: "radioButton" },
  { label: "进度条", value: "progress" },
  { label: "百分比组件", value: "percent" },
  { label: "数字输入框", value: "digit" },
  { label: "秒格式化", value: "second" },
  { label: "头像", value: "avatar" },
  { label: "代码框", value: "code" },
  { label: "开关", value: "switch" },
  { label: "相对于当前时间", value: "fromNow" },
  { label: "图片", value: "image" },
  { label: "代码框", value: "jsonCode" },
  { label: "颜色选择器", value: "color" },
  { label: "级联选择器", value: "cascader" },
  { label: "分段器", value: "segmented" },
  { label: "分组", value: "group" },
  { label: "表单列表", value: "formList" },
  { label: "表单集合", value: "formSet" },
  { label: "分割线", value: "divider" },
  { label: "依赖项", value: "dependency" },
];

const ColumnSet = ({ columns, changeColumns }) => {
  console.log("====================================");
  console.log(columns);
  console.log("====================================");

  const [activeId, setActiveId] = useState(null);
  const sensors = useSensors(useSensor(MouseSensor), useSensor(TouchSensor));
  const [form] = Form.useForm();

  return (
    <>
      {columns?.length > 0 && (
        <>
          <p className="ltitle0" style={{ marginTop: 12 }}>
            拖拽排序
          </p>
          <DndContext
            sensors={sensors}
            collisionDetection={closestCenter}
            onDragEnd={handleDragEnd}
            onDragStart={handleDragStart}
            onDragCancel={() => {
              setActiveId(null);
            }}
          >
            <SortableContext
              items={columns ?? []}
              strategy={rectSortingStrategy}
            >
              <div className="centerl" style={{ gap: 12 }}>
                {columns?.map?.((it, i) => (
                  <SortableItem key={it?.key ?? it?.dataIndex} item={it} />
                ))}
              </div>
            </SortableContext>
            <DragOverlay adjustScale style={{ transformOrigin: "0 0 " }}>
              {activeId ? (
                <Item
                  item={columns?.find((it) => it.key === activeId)}
                  isDragging
                />
              ) : null}
            </DragOverlay>
          </DndContext>
        </>
      )}

      <Divider></Divider>

      <ProForm
        form={form}
        submitter={false}
        onValuesChange={(val, allval) => {
          changeColumns(allval?.columns);
        }}
        autoFocusFirstInput={true}
      >
        <ProFormList
          name={"columns"}
          initialValue={columns}
          itemContainerRender={(doms) => {
            return <ProForm.Group>{doms}</ProForm.Group>;
          }}
          creatorRecord={() => {
            const uuid = uuidv4();
            return {
              key: uuid,
              search: false,
              valueType: "text",
            };
          }}
          copyIconProps={{
            Icon: CopyFilled,
            tooltipText: "复制此项到末尾",
          }}
          deleteIconProps={{
            Icon: DeleteFilled,
            tooltipText: "不需要这行了",
          }}
        >
          {(f, index, action) => {
            console.log(f, index, action);
            return (
              <>
                <ProFormText name="title" label="字段名" width="xs" />
                <ProFormText
                  name="key"
                  label="key"
                  width="xs"
                  allowClear={false}
                  required={true}
                  rules={[{ required: true, message: "" }]}
                />
                <ProFormDependency name={["title"]}>
                  {({ title }) => {
                    return (
                      <ProFormText
                        value={title}
                        name="dataIndex"
                        label="dataIndex"
                        width="xs"
                      />
                    );
                  }}
                </ProFormDependency>
                <ProFormSelect
                  name="valueType"
                  label="类型"
                  width="160px"
                  allowClear
                  showSearch
                  options={inputTypes}
                />

                <ProFormSwitch
                  name="search"
                  label="查询"
                  initialValue={false}
                ></ProFormSwitch>
                <ProFormSwitch
                  name="add"
                  label="新增"
                  initialValue={false}
                ></ProFormSwitch>
                <ProFormSwitch
                  name="edit"
                  label="编辑"
                  initialValue={false}
                ></ProFormSwitch>

                <ProFormSwitch
                  name="detail"
                  label="详情"
                  initialValue={false}
                ></ProFormSwitch>

                <div
                  style={{
                    display: "flex",
                    alignItems: index !== 0 ? "flex-start" : "flex-end",
                    gap: "8px",
                    height: 60,
                  }}
                >
                  <Button
                    type="dashed"
                    key="clear"
                    onClick={() => {
                      action.setCurrentRowData({
                        title: undefined,
                        dataIndex: undefined,
                      });
                    }}
                  >
                    清空此项
                  </Button>
                </div>
              </>
            );
          }}
        </ProFormList>
      </ProForm>
    </>
  );

  function handleDragStart(event) {
    setActiveId(event.active.id);
  }

  function handleDragEnd(event) {
    const { active, over } = event;

    if (active.id !== over.id) {
      const oldIndex = columns.map((it) => it.key).indexOf(active.id);
      const newIndex = columns.map((it) => it.key).indexOf(over.id);
      const newcolumns = arrayMove(columns, oldIndex, newIndex);
      changeColumns(newcolumns);
      form.setFieldsValue({
        columns: newcolumns,
      });
      setActiveId(null);
    }
  }
};

export default ColumnSet;
